<template>
  <div id="hospital">
    <div>
      <el-button
        size="small"
        type="success"
        icon="el-icon-circle-plus"
        @click="toAdd"
        >新增</el-button
      >
      <el-button
        size="small"
        type="danger"
        @click="handleDelete(null)"
        :disabled="multipleSelection.length == 0"
        icon="el-icon-remove"
        >批量删除</el-button
      >
      <div class="widthDiv marginLeft">
        <el-input
          size="small"
          clearable
          v-model="pageParam.name"
          placeholder="请输入医院名称"
        ></el-input>
      </div>
      <el-button
        size="small"
        icon="el-icon-search"
        type="warning"
        @click="toSearch"
        >搜索</el-button
      >
      <div class="lj">
        <el-button
          icon="el-icon-chat-line-square"
          type="info"
          size="primary"
          @click="gotolink"
          >医院详情介绍</el-button
        >
      </div>
    </div>

    <div class="tableDiv">
      <el-table
        max-height="488"
        size="small"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50"></el-table-column>

        <el-table-column type="index" label="序号" width="40"></el-table-column>
        <el-table-column
          prop="name"
          label="医院名称"
          width="200"
        ></el-table-column>
        <!-- <el-table-column prop="introduce" label="医院简介" width="120"></el-table-column> -->
        <el-table-column label="所属地址" width="160">
          <template slot-scope="scope"
            >{{ scope.row.province }}-{{ scope.row.city }}-{{
              scope.row.area
            }}</template
          >
        </el-table-column>
        <el-table-column
          prop="address"
          label="医院地址"
          width="80"
        ></el-table-column>
        <!-- <el-table-column prop="flags" label="标记" width="50"></el-table-column> -->
        <el-table-column
          prop="longitude"
          label="经度"
          width="70"
        ></el-table-column>
        <el-table-column
          prop="latitude"
          label="维度"
          width="70"
        ></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-chat-line-square"
              type="info"
              size="mini"
              @click="aa(scope.row)"
              >查看简介</el-button
            >

            <el-button
              icon="el-icon-edit"
              type="warning"
              size="mini"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              icon="el-icon-remove"
              size="mini"
              type="danger"
              @click="handleDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="j">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageParam.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageParam.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="visible"
      :before-close="beforeClose"
    >
      <el-dialog
        width="80%"
        :title="'获取' + (form.name || '') + '的经纬度'"
        :visible.sync="innerVisible"
        append-to-body
      >
        <el-amap
          :center="
            form.id
              ? [form.longitude, form.latitude]
              : [currentPosition.longitude, currentPosition.latitude]
          "
          vid="amapDemo1"
          :events="events"
          class="map"
        >
          <el-amap-marker
            vid="component-marker"
            :position="markerPosition"
          ></el-amap-marker>
        </el-amap>
        <!-- <el-amap v-else class="map" vid="amapDemo2" :events="events"></el-amap> -->
      </el-dialog>
      <el-form :model="form" ref="ruleForm" :rules="rules">
        <el-form-item prop="name" label="名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item
          prop="introduce"
          label="简介"
          :label-width="formLabelWidth"
        >
          <el-input
            type="textarea"
            v-model="form.introduce"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item prop="pca" label="省市区" :label-width="formLabelWidth">
          <el-cascader
            :props="{ value: 'label' }"
            v-model="form.pca"
            :options="regionData"
            @change="pcaChange"
          ></el-cascader>
        </el-form-item>

        <el-form-item
          prop="address"
          label="详细地址"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.address" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item prop="flags" label="标记" :label-width="formLabelWidth">
          <el-input v-model="form.flags" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item
          prop="longitude"
          label="经度"
          :label-width="formLabelWidth"
        >
          <el-input
            type="number"
            v-model="form.longitude"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item
          prop="latitude"
          label="纬度"
          :label-width="formLabelWidth"
        >
          <el-input
            type="number"
            v-model="form.latitude"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <span class="l">
          <el-button type="warning" @click="toselect('ruleForm')"
            >选取经纬度</el-button
          >
        </span>
        <span>
          <el-button type="danger" @click="toCancel">取 消</el-button>
          <el-button type="success" @click="toSave('ruleForm')"
            >确 定</el-button
          >
        </span>
      </div>
    </el-dialog>
    <!-- <el-button type="text" @click="dialogVisible = true">点击打开 Dialog</el-button>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <span>这是一段信息</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>-->

    <el-dialog
      title="医院简介"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span>{{ a }}</span>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="dialogVisible = false">取 消</el-button> -->
        <el-button
          icon="el-icon-check"
          type="success"
          @click="dialogVisible = false"
          >知道了</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { regionData } from "element-china-area-data";
// .代表当前文件的目录views  ..代表当前文件目录的上级目录
import axios from "../../utils/request.js";
export default {
  data() {
    return {
      a: "",
      dialogVisible: false,
      message: true,
      //当前地理位置对象
      currentPosition: {},
      markerPosition: [
        // this.currentPosition.longitude,
        // this.currentPosition.latitude
      ],
      events: {
        click: (e) => {
          this.markerPosition = [e.lnglat.lng, e.lnglat.lat];
          this.form.longitude = e.lnglat.lng;
          this.form.latitude = e.lnglat.lat;
        },
      },
      innerVisible: false,
      regionData,
      total: 0,
      pageParam: {
        page: 1,
        pageSize: 10,
        name: "",
      },
      multipleSelection: [],
      tableData: [],
      // 模态框的可见性  false为不可见，点击之后可见，变为true
      visible: false,

      // 模态框的数据
      form: {},

      // 表单控件标题的宽度
      formLabelWidth: "120px",
      // 模态框的标题
      title: "录入医院信息",
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        introduce: [{ required: true, message: "请输入描述", trigger: "blur" }],
        pca: [{ required: true, message: "请选择省市区", trigger: "blur" }],
        address: [
          { required: true, message: "请选择详细地址", trigger: "blur" },
        ],
        flags: [{ required: true, message: "请输入标记", trigger: "blur" }],
        // longitude: [{ required: true, message: "请输入经度", trigger: "blur" }],
        // latitude: [{ required: true, message: "请输入维度", trigger: "blur" }]
      },
    };
  },

  computed: {},
  methods: {
    gotolink() {
      //点击跳转至上次浏览页面
      //  this.$router.go(-1)

      //指定跳转地址
      this.$router.replace("/Introduce");
    },
    aa(r) {
      this.a = r.introduce;
      (this.dialogVisible = true), console.log(r);
    },
    toSearch() {
      this.pageParam.page = 1;
      this.pageQuery();
    },

    // handleClose(done) {
    //   this.$confirm("确认关闭？")
    //     .then(_ => {
    //       done();
    //     })
    //     .catch(_ => {});
    // },
    pcaChange(val) {
      this.form = {
        ...this.form,
        province: val[0],
        city: val[1],
        area: val[2],
      };
    },
    handleSizeChange(val) {
      this.pageParam.pageSize = val;
      this.pageQuery();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.pageParam.page = val;
      this.pageQuery();
    },

    async pageQuery() {
      let res = await axios.get("/hospital/pageQuery", {
        params: this.pageParam,
      });
      this.tableData = res.data.list;
      this.total = res.data.total;
    },

    handleSelectionChange(val) {
      // val是用户选中的数据对象数组
      this.multipleSelection = val.map((item) => item.id);
    },
    toBatchDelete() {
      console.log(res);
    },
    toCancel() {
      this.$refs["ruleForm"].resetFields();
      // alert(1);
      this.visible = false;
    },
    beforeClose(done) {
      this.$refs["ruleForm"].resetFields();
      done();
      // alert(1);
    },
    // 点击新增按钮
    toAdd() {
      this.form = {};
      this.markerPosition = [
        this.currentPosition.longitude,
        this.currentPosition.latitude,
      ];
      this.visible = true;
      this.title = "录入医院信息";
    },
    //编辑
    handleEdit(row) {
      this.title = "编辑医院信息";
      // 把row的值拿出来赋给form
      this.form = { ...row, pca: [row.province, row.city, row.area] };
      this.markerPosition = [this.form.longitude, this.form.latitude];
      this.visible = true;
    },
    async handleDelete(id) {
      // id就是要删除对象的id
      this.$confirm("真的要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res;
          if (id) {
            res = await axios.get("/hospital/deleteById", { params: { id } });
          } else {
            res = await axios.post("/category/batchDelete", {
              ids: this.multipleSelection.toString(),
            });
          }
          // 发请求删除
          // let res = await axios.get("/category/deleteById", { params: { id } });
          this.$notify({
            title: res.status == 200 ? "成功" : "失败",
            message: res.statusText,
            type: res.status == 200 ? "success" : "error",
          });
          this.pageQuery();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    toselect() {
      // this.$refs["ruleForm"].resetFields();
      this.$refs["ruleForm"].clearValidate();
      // this.message = false;
      // alert(1);
      this.visible = true;
      this.innerVisible = true;
    },
    //点击确定按钮
    toSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid && this.form.longitude != "" && this.form.latitude != "") {
          console.log(this.form, "====");
          axios.post("/hospital/saveOrUpdate", this.form).then((res) => {
            if (res.status == 200) {
              this.$notify({
                title: "成功",
                message: "保存成功",
                type: "success",
              });
              this.toCancel();
              //      alert(1);
              // // 保存成功 关闭模态框 刷新数据
              // this.visible = false;
              this.pageQuery();
            } else {
              this.$notify.error({
                title: "提示",
                message: "信息输入有误",
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },

  created() {
    this.pageQuery();
    //获取当前位置
    navigator.geolocation.getCurrentPosition(
      (data) => {
        // console.log(data, "当前地理位置信息");
        this.currentPosition = data.coords;
        this.markerPosition = [
          this.currentPosition.longitude,
          this.currentPosition.latitude,
        ];
      },
      (err) => {
        console.log(err);
      },
      {
        enableHighAccuracy: true, //高精度
        timeout: 5000, //超时时间
        maximumAge: 10000, //位置缓存时间
      }
    );
  },
};
</script>
<style  scoped>
.tableDiv {
  height: 460px;
}
.map {
  height: 300px;
}
.l {
  float: left;
  margin-left: 20px;
}
.widthDiv {
  width: 200px;
  display: inline-block;
  margin-right: 10px;
  margin-bottom: 10px;
}
.marginLeft {
  margin-left: 20px;
}
.j {
  margin-top: 40px;
}
.lj {
  float: right;
  margin-right: 50px;
}
</style>